package com.sunmi.sbs.commons.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * author: fanjia
 * date: 2020/9/22 14:56
 * file: HMACUtils.java
 */
public class HMACUtils {
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder SB = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                SB.append('0');
            }
            SB.append(stmp);

        }
        return SB.toString().toLowerCase();
    }

    public static String hmac256(String body, String key) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] digest = sha256_HMAC.doFinal(body.getBytes(StandardCharsets.UTF_8));
            return byteArrayToHexString(digest);
        }
        catch (Exception e){
            System.out.println("Error");
        }
        return null;
    }
    public static String hmac256(String body, byte[] key) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key, "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] digest = sha256_HMAC.doFinal(body.getBytes(StandardCharsets.UTF_8));
            return byteArrayToHexString(digest);
        }
        catch (Exception e){
            System.out.println("Error");
        }
        return null;
    }
}
